package com.glor.operation.common.utils;

import com.glor.operation.common.web.security.userdetails.DefaultUserDetails;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;

/**
 * Created by heylear.cai on 2016/2/18.
 */
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name) {
        Assert.notNull(applicationContext, "applicationContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        return (T) applicationContext.getBean(name);
    }

    public static Long getCurrentUserId(){
        try {
            DefaultUserDetails userDetails = (DefaultUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return userDetails == null ? 0l : userDetails.getUserId();
        } catch (Exception e) {
            return 0l;
        }
    }
}
